'use strict'

import fly from '@/utils/fly'

const OPENIDKEY = 'UserOpenid'
const SESSIONKEY = 'UserSessionKey'

let isLoading = false
let callbacks = []

export function getUnionid () {
  return new Promise((resolve, reject) => {
    wx.login({
      success: function (res) {
        fly.post(`Wechat/getOpenid?code=${res.code}`)
          .then((suc) => {
            if (suc && suc.code === 200 && suc.data) {
              resolve(suc)
            } else {
              reject(new Error('Wechat/getOpenid fail'))
            }
          }, (err) => {
            reject(err)
          })
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
}

export function getOpenid () {
  return new Promise((resolve, reject) => {
    let openid = ''
    try {
      openid = wx.getStorageSync(OPENIDKEY)
    } catch (e) {
      reject(e)
    }
    if (openid) {
      resolve(openid)
    } else if (isLoading) {
      callbacks.push(function (oid) {
        if (oid) {
          resolve(oid)
        } else {
          reject(new Error('Wechat/getOpenid fail'))
        }
      })
    } else {
      isLoading = true
      let handelCB = function (oid) {
        isLoading = false
        let tmp
        while ((tmp = callbacks.pop()) != null) {
          tmp(oid)
        }
      }
      wx.login({
        success: function (res) {
          fly.post(`Wechat/getOpenid?code=${res.code}`)
            .then((suc) => {
              if (suc && suc.code === 200 && suc.data) {
                const openid = suc.data.wx_openid
                try {
                  wx.setStorageSync(OPENIDKEY, openid)
                  wx.setStorageSync(SESSIONKEY, suc.data.session_key)
                } catch (e) {
                }
                resolve(openid)
                handelCB(openid)
              } else {
                reject(new Error('Wechat/getOpenid fail'))
                handelCB('')
              }
            }, (err) => {
              reject(err)
              handelCB('')
            })
        },
        fail: function (err) {
          reject(err)
          handelCB('')
        }
      })
    }
  })
}

export function clearOpenid () {
  return new Promise((resolve, reject) => {
    try {
      wx.removeStorageSync(OPENIDKEY)
      wx.removeStorageSync(SESSIONKEY)
    } catch (e) {
    }
    resolve()
  })
}
